// pages/order/order.js
import request from '../../utils/request'
import Dialog from '@vant/weapp/dialog/dialog';
import {getCartTotalPrice} from '../../utils/cartUtil'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: '',
    shoppingCartList: '',
    isFromAddress: false,
    estimatedTime:'',
    packingCharge:'',
    total:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    // 发送请求，获取默认地址和购物车数据
    if (!this.data.isFromAddress) {
      const {
        result: address
      } = await request({
        url: "/user/addressBook/getDefault"
      })
      this.setData({
        address
      })

    }else{
      this.setData({
        isFromAddress:false
      })
    }
    const {
      result: shoppingCartList
    } = await request({
      url: '/user/shoppingCart/list'
    })
    
    this.setData({
      shoppingCartList
    })
    // 显示预计到达时间
    const now=new Date()
    const estimated=new Date(now.getTime()+30*60*1000)
    const hours=estimated.getHours().toString().padStart(2,"0")
    const minutes=estimated.getMinutes().toString().padStart(2, '0')
    this.setData({
      estimatedTime: `${hours}：${minutes}到达`
    })
    // 计算打包费
    const packingCharge=this.data.shoppingCartList.reduce((total,current)=>total+=current.number,0)
    this.setData({
      packingCharge
    })
    // 计算总价
    const resultCartTotal=await getCartTotalPrice()
    this.setData({
      total:resultCartTotal+packingCharge+4
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  toChooseAddress() {
    wx.navigateTo({
      url: '/pages/address/address?type=2',
    })

  },
  async getAddressId(id,callback) {
    const {
      result
    } = await request({
      url: `/user/addressBook/getById/${id}`
    })
    // console.log(result);
    this.setData({
      address: result,
      isFromAddress:true
    },()=>{
      if(callback) callback()
    })
  },
  async onSubmitOrder(){
    const {address,packingCharge,total} =this.data
    Dialog.confirm({
      title: '温馨提示',
      message: '确认要添加订单吗?',
    })
      .then(async () => {
        const {result} = await request({
          method:"post",
          url:'/user/order/submit',
          data:{
           addressBookId:address.id,
           payMethod:1,
           remark:'',
           estimatedDeliveryTime:new Date(),
           deliveryStatus:1,
           tablewareNumber:packingCharge,
           tablewareStatus:1,
           packAmount:4,
           amount:total
          }
         })
        wx.navigateTo({
          url: `/pages/pay/pay?orderInfo=${encodeURIComponent(JSON.stringify(result))}`,
        })
      })
     

  }
})